#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SQL type wrappers audited by Joshua Kugler, 2008-02-20

"""Page vehicleinfo defines one function to select vehicle state and output
the data."""

from tack.db import query
from tack.lib import string_app, content_headers, status_codes, json_app
from tack.lib.jsontools import json_dumps
from tack.lib.dicttools import query_to_list
import time

get_all_vehicles = """
SELECT vehicle_id, vehicleno, tagno, capacity, doortype, weight, type, status
FROM tmpo_vehicle
WHERE active=1
"""

get_current_maint_state = """
SELECT tmpo_vehicle_unavailable.vehicle_id, tmpo_vu_type.description
FROM tmpo_vehicle_unavailable, tmpo_vu_type
WHERE tmpo_vehicle_unavailable.type=tmpo_vu_type.vu_type_id and 
((getdate() < tmpo_vehicle_unavailable.vu_end and getdate() > tmpo_vehicle_unavailable.vu_start) 
OR (tmpo_vehicle_unavailable.type = 2)) and tmpo_vehicle_unavailable.active=1
"""

get_vehicle_types = """
SELECT vt_id, vt_description
FROM tmpo_vehicle_type
"""

def get_vehicle_state(environ, start_response):
    """Function get_vehicle_state does something"""
    sql_statement = get_all_vehicles
    vehicle_data = query(environ['connection'], sql_statement)
    sql_statement = get_current_maint_state
    maint_data = query(environ['connection'], sql_statement)
    sql_statement = get_vehicle_types
    type_data = query(environ['connection'], sql_statement)
    output = {'vehicles':[]}
    proto = {}
    events = output['vehicles']
    for vehicle in vehicle_data:
        tmp = proto.copy()
        tmp = {
        'id':str(vehicle[0]),'vehicleno':str(vehicle[1]),'tagno':str(vehicle[2]),
        'capacity':str(vehicle[3]),'doortype':str(vehicle[4]),'weight':str(vehicle[5]),
        'status':str(vehicle[7])
         }
        ## TODO:  don't shadow the builtin
        for type in type_data:
            if vehicle[6] == type[0]:
                tmp['type'] = str(type[1])
        tmp['maint'] = "Available"
        for maint in maint_data:
            if vehicle[0] == maint[0]:
                tmp['maint'] = str(maint[1])        
        events.append(tmp)
    return json_app(output)(environ, start_response)
